import csv
import string
import time
from smap.driver import SmapDriver
from smap.util import periodicSequentialCall
import datetime, calendar
import smap.core as core
import smap.util as util

class nytBmsDriver(SmapDriver):
	
	def setup(self, opts):
		self.f = open('/home/cbe/BSG_share/bsg on 169.229.130.74/New York Times/BMS/nyt_all_bms_for_sMAP_EST.csv', 'rb')
		self.f2 = open('/home/cbe/BSG_share/bsg on 169.229.130.74/New York Times/BMS/NYTpointExplanations_for_sMAP.csv', 'rb')
		self.data = csv.reader(self.f)
		self.points = csv.reader(self.f2)
		self.headers = next(self.data)
		self.ids = {}
		new = '_'
		self.smapheaders = {}		
		#use another file to set description metadata and units
		self.names = next(self.points)	
		self.units = next(self.points)
		self.descriptions = next(self.points)
		
		for i in xrange(1,len(self.headers)):
			if self.headers[i] != '#N/A':
				self.smapheaders[i] = self.headers[i].replace('.', '/')
				self.smapheaders[i] = string.replace(self.smapheaders[i], ':', '/')
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'OCC/UNOCC', 'OCC_UNOCC')
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'HEAT/COOL', 'HEAT_COOL')
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'DSP/N', 'DSP_N')
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'DSP/S', 'DSP_S')    
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'CRA/DIFF', 'CRA_DIFF')
				self.smapheaders[i] = self.smapheaders[i].replace('CRA/SP', 'CRA_SP')
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'TZ/SP', 'TZ_SP')
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'TS/SP', 'TS_SP')
				self.smapheaders[i] = string.replace(self.smapheaders[i], 'TH/OFFSET', 'TH_OFFSET')
				
				if str.count(self.smapheaders[i], '/') > 3:
					li = self.smapheaders[i].rsplit('/',1)
					self.smapheaders[i] = new.join(li)
				
				for j in xrange(0,len(self.names)):
					if self.headers[i] == self.names[j]:
						self.smapunit = self.units[j]
						break
					else:
						self.smapunit = 'NA'
				ts = self.add_timeseries('/%s' % self.smapheaders[i], '%s' % self.smapunit, data_type="double")
				self.ids[i] = ts['uuid']
				
				#print self.smapheaders[i]
				
				for j in xrange(0,len(self.names)):
					if self.headers[i] == self.names[j]:
						self.set_metadata('/' + self.smapheaders[i], {
	            		'Extra/Description' : str(self.descriptions[j]), 
	              		})
						break
						
		self.period = opts.get("Period", 1000000)

	def start(self):
		periodicSequentialCall(self.read).start(self.period)
	
	def read(self):
		errorCount = 0
		"""In the reactor thread, send the data to sMAP"""
		keyOn = set(['OCC','COOL','ON','START','ENABLED','OPEN','RUN','YES','C','ENABLE','TART','COOOO','OOL'])
		keyOff = set(['UNOCC','HEAT','OFF','STOP','DISABLED','CLOSED','DISABL','NO','H','CLOOOD','OFFFF'])
		for row in self.data:
			datetime = row[0]
			print datetime
			smaptime = calendar.timegm(time.strptime(datetime, '%m/%d/%Y %H:%M')) + 3600*5
			for i in xrange(1,len(self.smapheaders)):
				if row[i] != '#N/A' and row[i] != '':
					#print row[i]
					if len(keyOn.intersection(set([row[i]]))) != 0:
						row[i] = 1
						self.add(self.ids[i], smaptime, float(row[i]))
					elif len(keyOff.intersection(set([row[i]]))) != 0:
						row[i] = 0
						self.add(self.ids[i], smaptime, float(row[i]))
					else:
						try:
							float(row[i])
						except ValueError:
							errorCount += 1
						else:
							self.add(self.ids[i], smaptime, float(row[i]))
		print errorCount
					#print self.ids[i],smaptime,row[i]
					
		
		self.f.close()
		self.f2.close()
